//
//  WBHomeController.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/14.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBHomeController.h"
#import "UIBarButtonItem+Item.h"
#import "WBTestViewController.h"
#import "WBVisitorView.h"

#import "WBOAuthViewModel.h"
#import "WBGetStatusesViewModel.h"
#import "WBStatuseInfoViewModel.h"
#import "WBStatusesModel.h"
#import <SVProgressHUD.h>
#import "WBHomeCell.h"

#import "WBRefreshView.h"

#import "JPFPSStatus.h"

@interface WBHomeController ()

@property(nonatomic ,strong) NSArray<WBStatuseInfoViewModel *>* arrayModels;

@property(nonatomic ,weak) UIActivityIndicatorView *indicator;

@property(nonatomic ,strong) WBRefreshView *refreshView;

@property(nonatomic ,strong) UILabel *countLable;


/**
 快速拖拽需要刷新的数组
 */
@property(nonatomic ,strong) NSMutableArray<NSIndexPath *> *needLoadArray;

@end


static NSString *cell_ID = @"WBHomeCell_ID";
static NSString *WBRetwwetCell_ID = @"WBRetwwetCell_ID";
@implementation WBHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[JPFPSStatus sharedInstance] open];
    
    self.navItem.rightBarButtonItem = [UIBarButtonItem itemWithimage:[UIImage imageNamed:@"navigationbar_pop"] highImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(push)];
    
    if (self.tableV == nil) {
        
        [self.visitorV title:@"我是首页我是首页我是首页我是首页我是首页我是首页" imageName:@"visitordiscover_feed_image_smallicon" isHome:true];
        return;
    }
    
    [self loadData];
    [self setupTableView];
    
}

#pragma mark : - 加载数据
-(void)loadData{
    
    WBGetStatusesViewModel *arrayModel = [WBGetStatusesViewModel shared];
    
    [arrayModel loadData:_indicator.isAnimating completion:^(BOOL isSuccess, NSInteger count) {
        if (!isSuccess) {
            
            [SVProgressHUD showErrorWithStatus:@"网络有❌，请重新再试哦，思密达"];
            [_refreshView stopRefreshing];
            return ;
        }
        
        NSLog(@"👌");
        if (!_indicator.isAnimating) {
            //设置刷新几条微博动画
            [self setWeiboCountAnimation:count];
        }
        
        self.arrayModels = arrayModel.arrayStatuses;
        
        [_refreshView stopRefreshing];
        
        [_indicator stopAnimating];
        
        [self.tableV reloadData];
    }];
    

}

-(void)setWeiboCountAnimation:(NSInteger)count {
    
    if (!self.countLable.hidden) {
        
        return;
    }
    if (count == 0) {
        
        self.countLable.text = @"已经是最新微博";
    }else{
    
        self.countLable.text = [NSString stringWithFormat:@"已经更新了%zd条微博",count];
    }
    
    self.countLable.hidden = NO;
    self.countLable.alpha = 1;
    [UIView animateWithDuration:1 animations:^{
        
        self.countLable.frame = CGRectMake(0, NAVHeight, kUISCRRENW, 37);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:2 animations:^{
            
            self.countLable.frame = CGRectMake(0, NAVHeight - 37, kUISCRRENW, 37);
            self.countLable.alpha = 0;
        } completion:^(BOOL finished) {
            
            self.countLable.hidden = YES;
        }];
    
    }];
    
}


/**
 设置tableview
 */
-(void)setupTableView{

    //原创微博
    UINib *nib = [UINib nibWithNibName:@"WBHomeCell" bundle:nil];
    [self.tableV registerNib:nib forCellReuseIdentifier:cell_ID];
    //转发微博
    UINib *nib2 = [UINib nibWithNibName:@"WBRetwwetCell" bundle:nil];
    [self.tableV registerNib:nib2 forCellReuseIdentifier:WBRetwwetCell_ID];
    
    //设置上拉刷新控件
    [self setupPullupRefresh];
    
    //设置下拉刷新
    _refreshView = [[WBRefreshView alloc]init];
    
    [_refreshView addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
    
    [self.tableV addSubview:_refreshView];
    
    _countLable = [UILabel cz_labelWithText:@"" fontSize:15 color:[UIColor whiteColor]];
    
    _countLable.backgroundColor = [UIColor orangeColor];
    _countLable.hidden = YES;
    
    _countLable.frame = CGRectMake(0, NAVHeight - 37, kUISCRRENW, 37);
    [self.view insertSubview:_countLable belowSubview:self.navBar];
}
#pragma mark : - 设置上拉刷新控件
-(void)setupPullupRefresh{

    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    indicator.color = [UIColor cz_randomColor];
    
    _indicator = indicator;
    
    self.tableV.tableFooterView = indicator;
    
}


-(void)push{
    
    WBTestViewController *vc = [[WBTestViewController alloc]init];

    [self.navigationController pushViewController:vc animated:YES];

}


#pragma mark : - tableview数据源方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.arrayModels.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    WBStatuseInfoViewModel *model = self.arrayModels[indexPath.row];
    NSString *cellid;
    if (model.statuse.retweeted_status == nil) {
        
        cellid = cell_ID;
        
    }else{
    
        cellid = WBRetwwetCell_ID;
    }
    
    WBHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid forIndexPath:indexPath];
    
    //如果需要加载的数组的数量大于0 并且 正要加载的indexPath不在按需加载的数组中 就不渲染cell
    if (self.needLoadArray.count > 0 ) {
        
        if (![self.needLoadArray containsObject:indexPath]) {
            
            NSLog(@"忽略加载");
            return cell;
        }
        
    }
    
    cell.model = model;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark : - 自动计算行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    WBStatuseInfoViewModel *model = self.arrayModels[indexPath.row];
    
    return model.rowHeight;
}

#pragma mark : - 向上拉刷新代理方法
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    if ((indexPath.row == self.arrayModels.count - 2) && !_indicator.isAnimating){
        
        [_indicator startAnimating];
        
        [self loadData];
    }
    
}

-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{

    NSIndexPath *ip = [self.tableV indexPathForRowAtPoint:CGPointMake(0, targetContentOffset->y)];
    NSIndexPath *cip = [[self.tableV indexPathsForVisibleRows] firstObject];
    
    NSInteger skipCount = 12;
    
    if (ABS(cip.row - ip.row) > skipCount) {
        
        NSArray<NSIndexPath *> *temp = [self.tableV indexPathsForRowsInRect:CGRectMake(0, targetContentOffset->y, kUISCRRENW, self.tableV.bounds.size.height)];
        
        NSMutableArray *arrayM = temp.mutableCopy;
        //向下滑动
        if (velocity.y < 0) {
            
            NSIndexPath *indexPath = arrayM.lastObject;
            /*if (indexPath.row + 3 < self.statusesViewModel.arrayStatuses.count) {
             arr.append(IndexPath(row: indexPath.row + 1, section: 0))
             arr.append(IndexPath(row: indexPath.row + 2, section: 0))
             arr.append(IndexPath(row: indexPath.row + 3, section: 0))
             }*/
            if (indexPath.row + 3 < self.arrayModels.count) {
                
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0]];
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row + 2 inSection:0]];
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row + 3 inSection:0]];
                
            }
        }else{
          //向上滑动
            NSIndexPath *indexPath = arrayM.firstObject;
            if (indexPath.row - 3 < self.arrayModels.count) {
                
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row - 3 inSection:0]];
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row - 2 inSection:0]];
                [arrayM addObject:[NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0]];
        }
    }
    
        self.needLoadArray = arrayM;
  }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    [self.needLoadArray removeAllObjects];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [self.needLoadArray removeAllObjects];
}

@end
